<?php
error_reporting(0);
session_start();
if(!isset($_SESSION['username'])){
    // echo '<script>alert("未登录");location="./login.html"</script>';
    exit(0);
}

$bookurl = $_POST['bookurl'];
$html = file_get_contents("$bookurl");
$html = mb_convert_encoding($html,'UTF-8','UTF-8,GBK,GB2312,BIG5');//转码
$htmlOneLine = preg_replace("/\r|\n|\t/","",$html); //去除空格换行等
preg_match("/<title>(.*)<\/title>/iU",$htmlOneLine,$titleArr);
if($html){
    $bookname = $titleArr[1];
}else{
    $bookname = '无法获取';
}
$bookicon = $_POST['bookicon'];
$bookcata = $_POST['bookcata'];
$bookuser = $_SESSION['username'];

if ($bookurl == '') {
    // echo '<script>alert("不能为空");history.go(-1);</script>';
    exit(0);
}
if (strlen($bookurl) >256) {
    // echo '<script>alert("内容过长");history.go(-1);</script>';
    exit(0);
}

include('./connect.php');
if ($conn->connect_error) {
    // echo '数据库连接失败！';
    exit(0);
} else {
    
    $sql_insert = "insert into book (book_icon,book_name,book_url,book_cata,book_user) values('$bookicon','$bookname','$bookurl','$bookcata','$bookuser')";
    $res_insert = $conn->query($sql_insert);

    $sql_select = "select book_id from book where book_user = '$bookuser' order by book_id desc";
    $res_select = $conn->query($sql_select);
    $number_select = mysqli_num_rows($res_select);
    if ($number_select) {
        $row = mysqli_fetch_assoc($res_select);
        $bookid = $row['book_id'];
        echo json_encode(array(
            'bookid' => $bookid,
            'bookname' => $bookname,
        ));
    }

    if (!$res_insert) {
        // echo "<script>alert('系统繁忙，请稍候！');</script>";
    }
}

?>